<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="活动名称">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <vue-editor
          v-model="form.content"
          :useCustomImageHandler="true"
          @image-added="imgUpload"
        />
      </el-form-item>
      <el-form-item label="栏目">
        <el-checkbox-group v-model="checkList">
          <el-checkbox v-for="cate of cateList" :key="cate.id" :label="cate.id">
            {{ cate.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="封面">
        <el-upload
          :action="$axios.defaults.baseURL + '/upload'"
          :headers="{ Authorization: headers }"
          list-type="picture-card"
          :on-remove="handleRemove"
          :on-success="handleUpload"
          :file-list="form.cover"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="类型">
        <el-radio-group v-model="form.type">
          <el-radio :label="1">文章</el-radio>
          <el-radio :label="2">视频</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">发布文章</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { VueEditor } from "vue2-editor";
export default {
  name: "EditPost",
  components: {
    VueEditor,
  },
  data() {
    return {
      headers: "Bearer " + window.localStorage.token,
      cateList: [], // 这个是用来渲染数据的
      checkList: [], // 这个是用来绑定给复选框组的
      form: {
        title: "",
        content: "",
        // categories上传的格式必须是[{id:1},{id:2}]这样的，而如果直接将categories绑定给复选框组的话，假设选中的两个复选框的label属性值是1,2，拿到的数据是这样的[1,2]，所以需要借助另外一个变量checkList绑定到复选框组，监听他的变化，从而进行格式转换。
        categories: [],
        cover: [], // 上传的封面图
        type: 1,
      },
    };
  },
  watch: {
    // 一旦复选框组发生变化就
    checkList() {
      this.form.categories = this.checkList.map((item) => {
        return {
          id: item,
        };
      });
    },
  },
  mounted() {
    if (this.$route.query.id) {
      this.renderData();
    }
    this.getCategories();
  },
  methods: {
    renderData() {
      this.$axios.get("/post/" + this.$route.query.id).then((res) => {
        let data = res.data.data;
        // console.log(data);
        // 把文章内容的div换成p,否则富文本组件会报错
        data.content = data.content.replace(/div/g, "p");
        // 处理多选框问题
        this.checkList = data.categories.map((item) => {
          return item.id;
        });
        // 处理图片问题
        data.cover = data.cover.map((item) => {
          if (item.url.indexOf("http") === -1) {
            item.url = this.$axios.defaults.baseURL + item.url;
          }
          return item;
        });
        this.form = data;
      });
    },
    handleRemove(file, fileList) {
      this.form.cover = fileList;
    },
    handleUpload(res, file) {
      file.id = res.data.id;
      this.form.cover.push(file);
    },
    getCategories() {
      this.$axios.get("/category").then((res) => {
        let list = res.data.data;
        list.shift(); // 删除推荐和关注栏目，这两个是默认有的
        list.shift();
        this.cateList = list;
      });
    },
    onSubmit() {
      // console.log(this.form);
      this.$axios.post("/post", this.form).then((res) => {
        // console.log(res);
        if (res.data.message === "文章发布成功") {
          this.$message.success("发布成功");
          this.$router.replace("/postlist");
        }
      });
    },
    // 富文本自定义上传文件
    imgUpload(File, Editor, cursorLocation, resetUploader) {
      let data = new FormData();
      data.append("file", File);
      this.$axios({
        method: "post",
        url: "/upload",
        data,
      }).then((res) => {
        // console.log(res);
        if (res.data.message === "文件上传成功") {
          const url = this.$axios.defaults.baseURL + res.data.data.url;
          // 要把这张图片放入编辑器的光标所在位置
          // 下面是富文本框的固定 api 写法
          Editor.insertEmbed(cursorLocation, "image", url);
          // 另一个固定写法，插入图片后必须复原上传组件
          resetUploader();
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
/deep/ .quillWrapper .ql-snow.ql-toolbar {
  line-height: 1;
}
</style>
